package admin.controllers;

import helpers.StringHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import debugs.DealDebug;

import models.DealEmailModel;
import models.DealModel;
import models.GeoModel;

import admin.data.DealData;
import admin.data.DealEmailData;
import admin.data.GeoData;

public class PreviewDealEmailServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		String path = ((HttpServletRequest) request).getRequestURI();

		String id = "";
		try {
			id = URLDecoder.decode(
					path.toLowerCase().replaceAll("/print/dealsemail/preview/",
							""), "UTF-8").toUpperCase();
		} catch (Exception e) {
			response.sendRedirect("/admin/dealsemail/list");
			return;
		}
		DealEmailData dealEmailData = new DealEmailData();
		DealEmailModel dealEmail = dealEmailData.get(id);

		DealData dealData = new DealData();
		ArrayList<DealModel> deals = new ArrayList<DealModel>();

		if (dealEmail == null) {
			response.sendRedirect("/admin/dealsemail/list");
			return;
		}

		GeoData geoData = new GeoData();
		GeoModel city = geoData.getGeo(dealEmail.getCity());

		List<String> ids = StringHelper.stringToList(dealEmail.getIds(), ",");
		deals = dealData.getByListId(ids);

		request.setAttribute("dealEmail", dealEmail);
		request.setAttribute("deals", deals);
		request.setAttribute("city", city);
		try {
			request.getRequestDispatcher("/admin/pages/preview_deal_email.jsp")
					.forward(request, response);
		} catch (ServletException e) {
			// e.printStackTrace();
		}
	}
}